//
//  ViewController.m
//  Gomoku
//
//  Created by Sekorm on 16/7/25.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "ViewController.h"
#import "CheckerboardView.h"
#define ScreenW [UIScreen mainScreen].bounds.size.width

@interface ViewController ()
@property (nonatomic,weak) CheckerboardView * boardView;
@property (nonatomic,weak) UIButton * backButton;
@property (nonatomic,weak) UIButton * reStartBtn;
@property (nonatomic,weak) UIButton * changeBoardButton;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUp];
    
}


- (void)setUp{
    
    self.view.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8];
    
    UIImageView * imgView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:imgView];
    imgView.image = [UIImage imageNamed:@"zhuziIcon"];
    
      
    
    //添加棋盘
    CheckerboardView * boardView = [[CheckerboardView alloc]initWithFrame:CGRectMake(20, 30, ScreenW * 0.95, CGFLOAT_MAX)];
    boardView.block = ^{
        [self alert];
    };
    boardView.center = self.view.center;
    [self.view addSubview:boardView];
    self.boardView = boardView;
    
    
    //悔棋
    UIButton * changeBoardButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [changeBoardButton setTitle:@"Elementary" forState:UIControlStateNormal];
    [changeBoardButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    changeBoardButton.backgroundColor = [UIColor lightGrayColor];
    changeBoardButton.frame = CGRectMake(CGRectGetMidX(boardView.frame) - CGRectGetWidth(boardView.frame) * 0.3, CGRectGetMinY(boardView.frame) - 50, CGRectGetWidth(boardView.frame) * 0.6, 35);
    changeBoardButton.layer.cornerRadius = 4;
    [self.view addSubview:changeBoardButton];
    self.changeBoardButton = changeBoardButton;
    [changeBoardButton addTarget:self action:@selector(changeBoard:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //悔棋
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setTitle:@"Back" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    backButton.backgroundColor = [UIColor lightGrayColor];
    backButton.frame = CGRectMake(CGRectGetMinX(boardView.frame), CGRectGetMaxY(boardView.frame) + 15, CGRectGetWidth(boardView.frame) * 0.45, 30);
    backButton.layer.cornerRadius = 4;
    [self.view addSubview:backButton];
    self.backButton = backButton;
    [backButton addTarget:self action:@selector(backOneStep:) forControlEvents:UIControlEventTouchUpInside];
    
    //新游戏
    UIButton * reStartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [reStartBtn setTitle:@"NewGame" forState:UIControlStateNormal];
    reStartBtn.backgroundColor = [UIColor lightGrayColor];
    reStartBtn.frame = CGRectMake(CGRectGetMaxX(boardView.frame) - CGRectGetWidth(boardView.frame) * 0.45, CGRectGetMaxY(boardView.frame) + 15, CGRectGetWidth(boardView.frame) * 0.45, 30);
    reStartBtn.layer.cornerRadius = 4;
    [self.view addSubview:reStartBtn];
    self.reStartBtn = reStartBtn;
    [reStartBtn addTarget:self action:@selector(newGame) forControlEvents:UIControlEventTouchUpInside];
}

- (void)alert{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Now,do you need starting a game ?"                                                             message:nil                             preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* sendAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
                                                           [self newGame];
                                                       }];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault                                      handler:^(UIAlertAction * action) {
    }];
    [alert addAction:cancelAction];
    [alert addAction:sendAction];
    //弹出
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)backOneStep:(UIButton *)sender{
    [self.boardView backOneStep:(UIButton *)sender];
}

- (void)newGame{
    
    [self.boardView newGame];
}

- (void)changeBoard:(UIButton *)btn{

    [self.boardView changeBoardLevel];
    [_changeBoardButton setTitle:[btn.currentTitle isEqualToString:@"Expert"]?@"Elementary":@"Expert" forState:UIControlStateNormal];
}


/*手机号码验证*/
+(BOOL)isValidateMobile:(NSString *)mobile
{
    //1开头，11位数字
    NSString *phoneRegex =@"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";//@"^(1)\\d{10}$";//
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
/** 是否是有效的注册帐号 */
+(BOOL)isValidateUserCount:(NSString *)userCount
{
    NSString *userCountRegex = @"^[0-9]{6,16}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:userCount];
}
/** 是否是有效的注册昵称，不包含特殊字符 */
+(BOOL)isValidateUserPitName:(NSString *)pitName
{
    NSString *pitNameRegex = @"^[\u4e00-\u9fa5A-Z0-9a-z_-]*$";
    NSPredicate *userPitName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pitNameRegex];
    return [userPitName evaluateWithObject:pitName];
}

/** 是否是身份证  */
+ (BOOL)isValidateIDCard:(NSString *)idcard
{
    BOOL flag;
    if (idcard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:idcard];
}
/** 是否输入的数字（整数） */
+(BOOL)isNumber:(NSString *)tring
{
    if ([self stringIsNullOrNil:tring]) {
        return NO;
    }
    NSString *regex2 = @"[0-9]{1}$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:tring];
}
/** 密码格式是否正确  */
+(BOOL)isPassword:(NSString *)password
{
    NSString *userCountRegex = @"^[0-9a-zA-Z]{6,16}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:password];
}
/** 支付密码格式是否正确  */
+(BOOL)isPayPassword:(NSString *)password
{
    NSString *userCountRegex = @"^[0-9]{6}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:password];
}
/** 判断字符串是否为空  */
+(BOOL)stringIsNullOrNil:(NSString *)str
{
    if((NSNull *)str ==[NSNull null] || str ==nil || [@"" isEqualToString:str]){
        return YES;
    }
    //去掉前后空格
    NSString *string = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (string.length==0) {
        return YES;
    }
    return NO;
}
+(double)getDoubleValueByString:(NSString *)str
{
    NSDecimalNumber *number =[NSDecimalNumber decimalNumberWithString:str];
    double doubleValue = [number doubleValue];//这里一定要用double不能用float或CGFloat，否则序列号精度不准
    
    if (isnan(doubleValue)) {
        return 0;
    }
    return doubleValue;
}
/** 是否为空  */
+(BOOL)isNSnullOrNil:(id)object
{
    
    if((NSNull *)object ==[NSNull null] || object ==nil){
        return YES;
    }
    
    return NO;
}
/** 把字符串转化成int  */
+(NSInteger)stringToInt:(NSString *)str
{
    if(![self stringIsNullOrNil:str]){
        //先转成真正的字符串，原因是可能str表明看是NSString类型，但是真正是int,long隐式类型...
        NSString *string=[NSString stringWithFormat:@"%zd",[str integerValue]];
        return [string integerValue];
    }
    return 0;
}
/** 把字符串转化成int  */
+(CGFloat)stringToCGFloat:(NSString *)str
{
    if(![self stringIsNullOrNil:str]){
        
        NSDecimalNumber *number =[NSDecimalNumber decimalNumberWithString:str];
        double doubleValue = [number doubleValue];
        if (isnan(doubleValue)) {
            return 0.0;
        }
        //这里一定要用double不能用float或CGFloat，否则序列号精度不准
        return doubleValue;
    }
    return 0.0;
}

/** 访问数组 */
+(NSString *)indexOfArr:(NSArray *)arr index:(NSInteger)index
{
    if (arr.count > index) {
        return arr[index];
    }
    return @"";
}

/** 比较两个字符串是否相同  */
+(BOOL)isEqual:(NSString *)str1 str2:(NSString *)str2
{
    if ([self stringIsNullOrNil:str1] || [self stringIsNullOrNil:str2]) {
        return NO;
    }
    if([str2 isEqualToString:str1]){
        return YES;
    }
    
    return NO;
}


/** 根据英文逗号分隔 */
+(NSArray *)spliStringToArr:(NSString *)string
{
    if ([self stringIsNullOrNil:string]) {
        return nil;
    }
    NSArray *arr=[string componentsSeparatedByString:@","];
    return arr;
}
/** 根据数字得到中文数字 */
+(NSString *)getChineseNumByInteger:(NSInteger)num
{
    NSString *numStr=@"";
    switch (num) {
        case 1:
            numStr =@"一";
            break;
        case 2:
            numStr =@"二";
            break;
        case 3:
            numStr =@"三";
            break;
        case 4:
            numStr =@"四";
            break;
        case 5:
            numStr =@"五";
            break;
        case 6:
            numStr =@"六";
            break;
        case 7:
            numStr =@"七";
            break;
        case 8:
            numStr =@"八";
            break;
        case 9:
            numStr =@"九";
            break;
        case 10:
            numStr =@"十";
            break;
        case 11:
            numStr =@"十一";
            break;
        default:
            numStr =[NSString stringWithFormat:@"%zd",num];
            break;
    }
    return numStr;
}
/** 根据数字得到星期几 */
+(NSString *)getChineseNumByWeekInteger:(NSInteger)num
{
    NSString *numStr=@"";
    switch (num) {
        case 0:
            numStr =@"日";
            break;
        case 1:
            numStr =@"一";
            break;
        case 2:
            numStr =@"二";
            break;
        case 3:
            numStr =@"三";
            break;
        case 4:
            numStr =@"四";
            break;
        case 5:
            numStr =@"五";
            break;
        case 6:
            numStr =@"六";
            break;
        case 7:
            numStr =@"日";
            break;
        default:
            numStr =[NSString stringWithFormat:@"%zd",num];
            break;
    }
    return numStr;
}
/** 增加必填的星号 */
+(NSAttributedString *)addStartByStr:(NSString *)str;
{
    NSString *start =@"*";
    NSString *content =[NSString stringWithFormat:@"%@%@",start,str];
    NSMutableAttributedString *attStr =[[NSMutableAttributedString alloc]initWithString:content];
    NSRange range=[content rangeOfString:start];
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    return attStr;
}
/** 增加非的星号 */
+(NSAttributedString *)addNotStartByStr:(NSString *)str;
{
    NSString *start =@"*";
    NSString *content =[NSString stringWithFormat:@"%@%@",start,str];
    NSMutableAttributedString *attStr =[[NSMutableAttributedString alloc]initWithString:content];
    NSRange range=[content rangeOfString:start];
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
    return attStr;
}

/**
 🐟新增方法:
 */

//通过富文本实现图文混排:
+ (NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image
{
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    
    // 拼接
    [attrString appendAttributedString:textAttr];
    [attrString appendAttributedString:attachementAttr];
    
    return [attrString copy];
}

//通过富文本实现图文混排(可选择方向)
+ (NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image pictureIsLeft:(BOOL)IsLeft
{
    
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置图片的偏移:
    attachment.bounds = CGRectMake(0, -2,image.size.width, image.size.height);
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    if (IsLeft) {
        [attrString appendAttributedString:attachementAttr];
        [attrString appendAttributedString:textAttr];
    }
    else{
        // 拼接
        [attrString appendAttributedString:textAttr];
        [attrString appendAttributedString:attachementAttr];
    }
    
    return [attrString copy];
}

+(NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image textFont:(NSInteger)font pictureIsLeft:(BOOL)IsLeft
{
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置图片的偏移:
    attachment.bounds = CGRectMake(0, -2,image.size.width, image.size.height);
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    if (!text) {
        text = @"";
    }
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]}];
    if (IsLeft) {
        [attrString appendAttributedString:attachementAttr];
        [attrString appendAttributedString:textAttr];
    }
    else{
        // 拼接
        [attrString appendAttributedString:textAttr];
        [attrString appendAttributedString:attachementAttr];
    }
    
    return [attrString copy];
}


/** 获取导航栏下方的黑线*/
+ (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}



/** 传入一个字符串,分割成时分格式*/
+(NSInteger)spliTimeString:(NSString * )timeString index:(NSInteger)index
{
    NSArray * arr = [timeString componentsSeparatedByString:@":"];
    if (index == 0) {
        return [arr[0] integerValue];
    }
    else{
        return [arr[1] integerValue];
    }
}
//判断内容是否全部为空格  yes 全部为空格  no 不是
+ (BOOL) strIsAllBlankEmpty:(NSString *) str{
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}
/**
 *  判断字符串里是不是全是数字
 *
 *  @param string <#string description#>
 *
 *  @return <#return value description#>
 */
+(BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

/**将img变为黑白图片*/
+ (UIImage*) convertImageToGreyScale:(UIImage*) image
{
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    CGContextDrawImage(context, imageRect, [image CGImage]);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);
    return newImage;
}



@end
